# -*- coding: utf-8 -*-
# @Author   : SongLiangCheng
# @QQ       : 2192383945
# @Time     : 2022/11/29 13:14
# @File     : app.py 
# @Project  : scraping
# @Desc     : this is a toy
import argparse
import logging
import os
import sys
from urllib.parse import urlparse
import coloredlogs


from 博客园.config import CnblogConfiguration
# logging.DEBUG
# CRITICAL = 50
# FATAL = CRITICAL
# ERROR = 40
# WARNING = 30
# WARN = WARNING
# INFO = 20
# DEBUG = 10
# NOTSET = 0






def param_config(config):
    # 脚本参数
    parser = argparse.ArgumentParser(description='爬博客园的博客')
    parser.add_argument('--show-config', action='store_true', help='显示配置')
    parser.add_argument('--version', action='version', version='%(prog)s 2.0')
    parser.add_argument('--debug', action='store_true', help='全局debug, 所有应用打开debug')
    parser.add_argument('ini_file', nargs='?', type=str, default='config.ini',help='可选，单个ini风格的配置文件, 环境变量优先级更高')
    args = parser.parse_args()

    # 是否debug
    if args.debug:
        config.debug = True

    # 处理文件选项
    if args.ini_file:
        # 只要路径包含bin，就执行
        if 'bin' in args.ini_file.split('/'):
            os.system(args.ini_file)
            sys.exit(1)

        try:
            #  先配置覆盖，再环境变量覆盖
            config.load_config_file(args.ini_file)
        except Exception as e:
            logger.fatal(e)
            sys.exit(1)
    # 处理打印配置选项
    if args.show_config:
        config.show_config()

    return args


def log_config(config):
    formatter = logging.Formatter(config.formatter_string)

    # 定义root handler
    coloredlogs.install(fmt=config.formatter_string)  # 默认INFO

    # 定义logger
    logger = logging.getLogger(__file__)

    # 定义debug
    coloredlogs.install(fmt=config.formatter_string, level=logging.DEBUG if config.debug else logging.INFO)
    return logger

if __name__ == '__main__':
    # 命令行传递配置并解析
    config = CnblogConfiguration(config_debug=False)
    config.load_from_environment_variables()

    args = param_config(config)
    logger = log_config(config)
    logger.info(args)

    match urlparse(config.scrapy_url).netloc:
        case "www.cnblogs.com":
            from 博客园.blog import CnBlog
            blog = CnBlog(config=config)
            logger.debug(f'获取到的路径 {config.basepath}')
            blog.run(config.scrapy_url)
        case "blog.csdn.net":
            from CSDN爬虫.blog import CsDnBlog
            blog = CsDnBlog(config=config)
            logger.debug(f'获取到的路径 {config.basepath}')
            config.next_url = f"https://blog.csdn.net/community/home-api/v1/get-business-list?page=1&businessType=blog&noMore=false&username={config.username}"
            blog.run(config.next_url)
        case "blog.51cto.com":
            from fiveoneCto.blog import fiveoneCto
            blog = fiveoneCto(config=config)
            blog.run(config.scrapy_url)
